﻿using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Http;
using Common.Logging;
using Learun.Application.Base.AuthorizeModule;
using Learun.Application.Base.SystemModule;
using Learun.Application.Organization;
using Learun.Loger;
using Learun.Util;
using Learun.Util.Operat;
using Learun.Util.SqlSugar;
using log4net.Config;

namespace Learun.Application.Web.AppApi
{
    /// <summary>
    /// 登录
    /// </summary>
    [RoutePrefix("api/LoginApi")]
    [HandlerApiLogin(FilterMode.Ignore)]
    public class LoginApiController : WebApiControllerBase
    {
        #region 模块对象
        private UserIBLL userBll = new UserBLL();
        #endregion

        /// <summary>
        /// 查看system.config中的初始密码
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetInitialPassword()
        {
            var res = Config.GetValue("InitialPassword", "000000").ToString();
            return Success(res);
        }
        /// <summary>
        /// 用户名、密码登录
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码（md5加密）</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult CheckLogin(string username, string password)
        {
            try
            {
                #region 测试用，因为NET6的前端，有的用不了MD5
                MD5 md5 = MD5.Create();
                byte[] buffer = Encoding.UTF8.GetBytes(password);//将字符串转成字节数组
                byte[] byteArray = md5.ComputeHash(buffer);//调用加密方法
                StringBuilder sb = new StringBuilder();
                foreach (byte b in byteArray)//遍历字节数组
                {
                    sb.Append(b.ToString("x2"));//将字节数组转成16进制的字符串。X表示16进制，2表示每个16字符占2位
                }
                //password = sb.ToString(); 注释掉之后就是原本的机制
                #endregion
                #region 内部账户验证

                UserEntity userEntity = userBll.CheckLogin(username, password);


                #region 写入日志
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 1;
                logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
                logEntity.F_OperateAccount = username + "(" + userEntity.F_RealName + ")";
                logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : username;
                logEntity.F_Module = Config.GetValue("SoftName");
                #endregion

                if (!userEntity.LoginOk)//登录失败
                {
                    //写入日志
                    logEntity.F_ExecuteResult = 0;
                    logEntity.F_ExecuteResultJson = "登录失败:" + userEntity.LoginMsg;
                    logEntity.WriteLog();
                    int num = OperatorHelper.Instance.AddCurrentErrorNum();
                    return Fail(userEntity.LoginMsg, num);
                }
                else
                {
                    var operatorInfo = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_WebApi_6.1_PC", null);//写入缓存信息
                                                                                                                                //写入日志
                    logEntity.F_ExecuteResult = 1;
                    logEntity.F_ExecuteResultJson = "登录成功";
                    logEntity.WriteLog();
                    OperatorHelper.Instance.ClearCurrentErrorNum(); //成功了 就可以重置了
                    bool isFirstLogin = false;
                    if (userEntity.PasswordUpdateTime == null)//没有修改密码
                    {
                        isFirstLogin = true;
                    }
                    #region 权限相关
                    //用于是否可以锁定IO分配界面里的channel等
                    bool isIOModuleAdmin = true;
                    //userEntity.F_CompanyId
                    CompanyService companyService = new CompanyService();
                    var companyObj = companyService.GetList().FirstOrDefault(x => x.F_CompanyId == userEntity.F_CompanyId);
                    var Department = "";
                    if (companyObj != null)
                    {
                        Department = companyObj.F_FullName;
                        if (Department.Contains("轮机"))
                        {
                            Department = "轮机";
                        }
                        else
                        {
                            Department = "电气";
                        }
                    }
                    else
                    {
                        Department = "电气";
                    }

                    #endregion

                    return Success("登录成功", new
                    {
                        operatorInfo.token,
                        operatorInfo.loginMark,
                        operatorInfo.account,
                        userId = userEntity.F_UserId,
                        RealName = userEntity.F_RealName,
                        IsIOModuleAdmin = isIOModuleAdmin,
                        isFirstLogin,
                        Department = Department
                    });


                }
                #endregion
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HandlerApiLogin(FilterMode.Enforce)]
        [TokenAuthorize]
        public IHttpActionResult OutLogin()
        {
            try
            {
                var token = HttpContext.Current.Request.Headers["logintoken"] ?? "";
                var loginkey = HttpContext.Current.Request.Headers["loginkey"] ?? "";
                var userInfo = LoginUserInfo.Get();
                userBll.UpdateOpenId(userInfo.userId, "");//绑定微信ID 
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 1;
                logEntity.F_OperateTypeId = ((int)OperationType.Exit).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Exit);
                logEntity.F_OperateAccount = userInfo.account + "(" + userInfo.realName + ")";
                logEntity.F_OperateUserId = userInfo.userId;
                logEntity.F_ExecuteResult = 1;
                logEntity.F_ExecuteResultJson = "退出系统";
                logEntity.F_Module = Config.GetValue("SoftName");
                logEntity.WriteLog();
                OperatorHelper.Instance.EmptyCurrent(token, loginkey);
                return Success("退出系统");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 是否登录验证
        /// </summary>
        /// <param name="token">登录token</param>
        /// <param name="loginkey">登录标识</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult ValidateLogin(string token, string loginkey)
        {
            try
            {
                // 验证登录状态
                var res = OperatorHelper.Instance.IsOnLine(token, loginkey, "", "");
                var errmsg = "";
                //登录验证错误
                if (res == null || res.userInfo == null)
                {
                    errmsg = "权限验证失败，请联系管理员";
                }
                else if (res.stateCode == 0)
                {
                    errmsg = "用户登录过期";
                }
                else if (res.stateCode == -1)
                {
                    errmsg = "用户未登录";
                }
                if (!string.IsNullOrEmpty(errmsg))
                {
                    return Fail("验证失败", new { LoginResCode = res.stateCode, UserAccount = "", UserName = "" });
                }
                return Success(new { LoginResCode = res.stateCode, UserAccount = res.userInfo.account, UserName = res.userInfo.realName });
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
    }
}